<template>
  <div class="page-list-live">
    <ListTable
      ref="RefListTable"
      :loading="tableLoading"
      style="padding: 0 20px 40px 20px;"
      :table-data="tableData"
      :table-col="tableCol"
      @selectChange="handleSelectionChange"
    >
      <template slot="col1" slot-scope="scope">
        <el-button
          icon="el-icon-document"
          :loading="scope.row.loadingEdit"
          size="mini"
          style="margin-left: 0px; margin-right: 10px; padding-top: 0px; padding-bottom: 0px;"
          type="text"
          @click="handleRowDetails(scope.row)"
        >详情</el-button>
        <el-button
          :loading="scope.row.loadingDel"
          size="mini"
          type="text"
          icon="el-icon-delete"
          style="color: red; margin-left: 0px; margin-right: 10px; padding-top: 0px; padding-bottom: 0px;"
          @click="handleRowDel(scope.row)"
        >删除</el-button>
      </template>
    </ListTable>
    <InOutCave ref="InOutCave"></InOutCave>
  </div>
</template>
<script>
  import { parseTime } from '@/utils'
  import listMixin from '@/mixins/list'
  import InOutCave from './InOutCave.vue'
  import { tunnelIORecord } from '@/api/api'
  export default {
    components: { InOutCave },
    mixins: [listMixin],
    data() {
      return {
        // 删除的id
        deleteList: {
          id: ''
        },
        // 列表数据
        tableData: [],
        listTitle: [
          'employeeId',
          'employee.name',
          'employee.RFID',
          'employee.accessCardID',
          'employee.department.deptName',
          'employee.job.jobTitle',
          'employee.work.workName',
          'enterTime',
          'leaveTime',
          'id'
        ],
        // 列表标题
        tableCol: [
          { type: 'selection' },
          { type: 'index', label: '序号', width: '60px' },
          {
            label: '员工名称',
            formatter(row, col, cell) {
              let deptName = ''
              if (row.employeeId) {
                deptName = row.employee.name
              }
              return deptName || ''
            },
            minWidth: '142px'
          },
          {
            label: 'RFID',
            formatter(row, col, cell) {
              let rfid = ''
              if (row.employeeId) {
                rfid = row.employee.rfid
              }
              return rfid || ''
            }
          },
          {
            label: '门禁ID',
            formatter(row, col, cell) {
              let number = ''
              if (row.employeeId) {
                number = row.employee.accessCardID
              }
              return number || ''
            },
            minWidth: '116px'
          },
          {
            label: '部门',
            formatter(row, col, cell) {
              return !row.employee ? '' : row.employee.department ? row.employee.department.deptName : ''
            }, minWidth: '130px'
          },
          {
            label: '职务',
            formatter(row, col, cell) {
              return !row.employee ? '' : row.employee.job ? row.employee.job.jobTitle : ''
            }
          },
          {
            label: '工种',
            formatter(row, col, cell) {
              return !row.employee ? '' : row.employee.work ? row.employee.work.workName : ''
            }
          },
          {
            label: '进入时间',
            formatter(row, col, cell) {
              return row.enterTime ? parseTime(new Date(row.enterTime).getTime()) : '--'
            },
            minWidth: '161px'
          },
          {
            label: '离开时间',
            formatter(row, col, cell) {
              return row.leaveTime ? parseTime(new Date(row.leaveTime).getTime()) : '--'
            },
            minWidth: '161px'
          },
          {
            label: '本次进场时长',
            formatter(row, col, cell) {
              if (!row.enterTime && !row.leaveTime) {
                return ''
              }
              if (!row.enterTime) {
                return ''
              }
              if (!row.leaveTime) {
                return ''
              }
              let date1 = new Date(row.enterTime) //开始时间
              let date2 = new Date(row.leaveTime) //结束时间
              let date3 = date2.getTime() - new Date(date1).getTime() //时间差的毫秒数

              //计算出相差天数
              let days = Math.floor(date3 / (24 * 3600 * 1000))

              //计算出小时数
              let leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
              let hours = Math.floor(leave1 / (3600 * 1000))

              //计算相差分钟数
              let leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
              let minutes = Math.floor(leave2 / (60 * 1000))

              return (days ? days + '天 ' : '') + hours + '小时 ' + minutes + '分钟'
            },
            minWidth: '161px'
          },
          { label: '操作', custom: 'col1', minWidth: '126px' }
        ]
      }
    },
    methods: {
      // 详情
      handleRowDetails(row) {
        let ary = []
        if (row.enterTime && row.employeeId) {
          ary = [{
            key: 'employeeId',
            value: row.employeeId,
            operation: 0,
            sequence: 0,
            relationship: 0
          }, {
            key: 'enterTime', value: parseTime(new Date(row.enterTime).getTime()-60*1000),
            operation: 4,
            sequence: 1,
            relationship: 0
          }, {
            key: 'leaveTime', value: row.leaveTime,
            operation: 5,
            sequence: 2,
            relationship: 0
          }]
        } else {
          this.$message.error('无进入时间无法查询！')
          return
        }
        let objData = {
          // 进入哪一个程序
          status: 'details',
          // 源数据
          row: row,
          // 源id
          id: row.id,
          // 查询参数
          searchData: {
            url: '/Path/Search',
            method: 'post',
            data: ary
          },
          apiKey: {
            search: '/Path/Search',
            add: '/Path',
            put: '/Path/'
          }
        }
        this.$refs['InOutCave'].openOne(objData)
        // this.$refs['InOutCave'].open(row, '/handleRowDetails')
      },
      // 选中事件
      handleSelectionChange(event) {
        if (event.length > 0) {
          let ary = []
          event.forEach(item => {
            ary.push(item.id)
          })
          if (ary.length > 1) {
            this.deleteList.id = ary.join(',')
          } else {
            this.deleteList.id = ary[0].toString()
          }
        } else {
          this.deleteList.id = ''
        }
        this.$emit('deleHandle', this.deleteList)
      },
      // 请求列表数据
      async getList(query) {
        this.tableLoading = true
        try {
          let obj = query || { pageIndex: 1, pageSize: 10, orderBy: 'updatedTime', orderByAscent: false, search: [] }
          if (!obj.search) {
            obj.search = []
          }
          // 如果选择空数据，需设置值为null
          obj.search.forEach((edit, index) => {
            if (edit.key === 'employee.department.id' && edit.value === '空') {
              edit.value = null
            } else if (edit.key === 'employee.work.id' && edit.value === '空') {
              edit.value = null
            }
          })
          if (!obj.search.some(r => r.key == 'CarId')) {
            obj.search.push({
              key: 'CarId',
              value: null,
              Operation: 0,
              relationship: 0,
              sequence: 0
            })
          }
          obj.select = this.listTitle
          const {
            data: { items: resData, count, pageIndex }
          } = await tunnelIORecord('POST', obj, false)

          this.$nextTick(() => {
            this.tableData = []
            resData.forEach(item => {
              item.loadingEdit = false
              item.loadingDel = false
              // if (item.employeeId) {
              //   this.tableData.push(item)
              // }
            })
            this.tableData = JSON.parse(JSON.stringify(resData))
            this.$refs['RefListTable'].update({ page: pageIndex, count })
            this.tableLoading = false
          })
        } catch (err) {
          this.tableLoading = false
          this.tableData = []
        }
      },
      async delRowReq(row) {
        try {
          const obj = { id: row.id, value: null }
          await tunnelIORecord('delete', obj, true)
          row.loadingDel = false
          this.getList(this.serchObj)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        } catch (err) {
          row.loadingDel = false
          this.$message.error('删除失败！')
        }
      },
      handleRowDel(row) {
        row.loadingDel = true
        this.$_delConfirm(
          '该进出场记录',
          () => {
            this.delRowReq(row)
          },
          () => {
            row.loadingDel = false
          }
        )
      }
    }
  }
</script>

<style lang="scss" scoped></style>
